package com.union.wx;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class ShareUtil {

	
	// 获取accessToken 微信地址
	public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

	// 获取ticket  微信地址
	public static final String GET_SIGNATURE_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
	
	public static String getSignature(String jsapi_ticket,String url,String nonce_str,String timestamp) {
        String string1;
        String signature = "";
 
        // 注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str
                + "&timestamp=" + timestamp + "&url=" + url;
 
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
 
            System.out.println("[signature] = " + signature);
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 
 
        return signature;
    }
    
	
	private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
	
	// 获取access_token
    public static String getToken(String appid, String secret){
    	//拼接访问地址
    	String turl = String.format("%s?grant_type=client_credential&appid=%s&secret=%s", GET_TOKEN_URL,appid, secret);
       
        HttpClient client = new DefaultHttpClient();
        //get请求
        HttpGet get = new HttpGet(turl);
        // 初始化解析json格式的对象
        JsonParser jsonparer = new JsonParser();
        String result = null;
        try
        {
            HttpResponse res = client.execute(get);
            String responseContent = null; // 初始化响应内容
            HttpEntity entity = (HttpEntity) res.getEntity();
            //设置编码格式
            responseContent = EntityUtils.toString((org.apache.http.HttpEntity) entity, "UTF-8");
            // 将json字符串转换为json对象
            JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
            
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                if (json.get("errcode") != null){
                	// 错误时微信会返回错误码等信息，{"errcode":40013,"errmsg":"invalid appid"}
                	}
                else{
                	// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    result = json.get("access_token").getAsString();
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally{
            // 关闭连接 ,释放资源
            client.getConnectionManager().shutdown();
            return result;
        }
    }

    // 获取getTicket
    public static String getTicket(String access_token){  
    	
    	String turl = String.format("%s?access_token=%s&type=jsapi",GET_SIGNATURE_URL,access_token);
    	
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(turl);
        
        JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
        String result = null;
        try
        {
            HttpResponse res = client.execute(get);
            String responseContent = null; // 响应内容
            HttpEntity entity = res.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
            JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
            
            // 将json字符串转换为json对象
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                if (json.get("errcode") == null){
                	// 错误时微信会返回错误码等信息，{"errcode":40013,"errmsg":"invalid appid"}
                }
                else{
                	// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    result = json.get("ticket").getAsString();
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            // 关闭连接 ,释放资源
            client.getConnectionManager().shutdown();
            return result;
        }
    }
}
